<template>
  <div>
    <a-card :bordered="false">
      <a-row>
        <a-col :span="2">
          <a-avatar :size="70" :src="userInfo.avatar" />
        </a-col>
        <a-col :offset="2">
          <p style="font-size: 15px">
            Hello, administrator <b>{{ userInfo.name }}</b> . Today is
            {{ time.weekday }} {{ time.month }} {{ time.day }} {{ time.year }}.
          </p>
          ID: {{ userInfo.id }}
        </a-col>
      </a-row>
    </a-card>
    <a-row style="margin-top: 0" :gutter="[24, 24]">
      <a-col :sm="24" :md="12" :xl="8">
        <a-card id="reader_card">
          <a-row>
            <a-col :span="12">
              <h1>READERS</h1>
              <a-icon slot="suffix" type="book" />
              <h1 style="font-size: 40px">{{ total_readers }}</h1>
              <a @click="changeContent(2)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/reader.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="8">
        <a-card id="fine_card">
          <a-row>
            <a-col :span="12">
              <h1>FINE</h1>
              <h1 style="font-size: 40px">{{ total_fine }}</h1>
              <a @click="changeContent(4)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/fine.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <!-- <a-col :sm="24" :md="12" :xl="8">
        <a-card id="fine_collected_card">
          <a-row>
            <a-col :span="12">
              <h1>FINE COLLECTED</h1>
              <h1 style="font-size: 40px">{{ total_fine_collected }}</h1>
              <a @click="changeContent(4)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/wallet.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col> -->

      <a-col :sm="24" :md="12" :xl="6">
        <a-card id="book_card">
          <a-row>
            <a-col :span="12">
              <h1>BOOKS</h1>
              <h1 style="font-size: 40px">{{ total_books }}</h1>
              <a @click="changeContent(1)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/book.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6">
        <a-card id="borrowing_card">
          <a-row>
            <a-col :span="12">
              <h1>BORROWING</h1>
              <h1 style="font-size: 40px">{{ total_borrowings }}</h1>
              <a @click="changeContent(3)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/borrowing_book.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6">
        <a-card id="damaged_card">
          <a-row>
            <a-col :span="12">
              <h1>DAMAGED</h1>
              <h1 style="font-size: 40px">{{ total_damaged_books }}</h1>
              <a @click="changeContent(1)">MORE INFO ></a>
            </a-col>
            <a-col :offset="15">
              <img src="../../assets/damaged_book.png" width="100" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6">
        <a-card id="lost_book_card">
          <a-row>
            <a-col :span="12">
              <h1>LOST</h1>
              <h1 style="font-size: 40px">{{ total_lost_books }}</h1>
              <a @click="changeContent(1)">MORE INFO ></a>
            </a-col>
            <a-col :offset="13">
              <img src="../../assets/lost_book.png" width="150" />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
    
    
    <div>
      <a-col>
        <p style="font-size: 20px">
            Hello, administrator. The following is the information of the books that are missing inventory. 
        </p>
      </a-col>
      <!-- 库存缺失的图书列表 -->
      <standard-table
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource1"
      >
        <div slot="barcode" slot-scope="{record}" style="width: 250px">
          <vue-barcode :value="record.key" style="width: 100%"></vue-barcode>
        </div>
        <div slot="description" slot-scope="{ text }" style="width: 100px; font-size: 50%">
          {{ text.slice(0, 50) }}...
        </div>
        <div slot="cover" slot-scope="{ record }">
          <img slot="avatar" size="large" shape="square" style="width:150px" :src="record.cover" />
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>

    <div>
      <a-col>
        <p style="font-size: 20px">
            Hello, administrator. Here is the information of the most popular books. 
        </p>
      </a-col>
      <!-- 最受欢迎的图书列表 -->
      <standard-table
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource2"
      >
        <div slot="barcode" slot-scope="{record}" style="width: 250px">
          <vue-barcode :value="record.key" style="width: 100%"></vue-barcode>
        </div>
        <div slot="description" slot-scope="{ text }" style="width: 100px; font-size: 50%">
          {{ text.slice(0, 50) }}...
        </div>
        <div slot="cover" slot-scope="{ record }">
          <img slot="avatar" size="large" shape="square" style="width:150px" :src="record.cover" />
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>
  </div>

  
</template>

<script>
import { getAccessToken, getUserInfo } from "@/services/user";
import category from './category'
import VueBarcode from '@chenfengyuan/vue-barcode';
import StandardTable from "@/components/table/StandardTable";
const columns = [
  {
    title: "cover",
    dataIndex: "cover",
    needTotal: true,
    scopedSlots: { customRender: "cover" },
  },
  {
    title: "title",
    dataIndex: "book_name",
  },
  {
    title: "introduction",
    dataIndex: "brief_introduction",
    scopedSlots: { customRender: "description" },
  },
  {
    title: "publisher",
    dataIndex: "publisher",
  },
  {
    title: "publish date",
    sorter: true,
    dataIndex: "published_time",
  },
  {
    title: "author",
    dataIndex: "author",
  },
  {
    title: "category",
    dataIndex: "category",
  },
    {
    title: "ISBN",
    dataIndex: "key",
    sorter: true
    // scopedSlots: {customRender: "barcode"}
  },
  // {
  //   title: "actions",
  //   scopedSlots: { customRender: "action" },
  // },
];

/**
{
    ISBN: "978-7-111-64577-1",
    book_name: "",
    bref_introduction: "",
    publisher: "",
    published_time: "",
    author: "",
    category: ""
}
*/
export default {
  name: "dashboard",
  components: { StandardTable, VueBarcode },
  data() {
    return {
      total_readers: "",
      total_books: "",
      total_book_copys: "",
      total_borrowings: "",
      total_fine: "",
      total_lost_books: "",
      total_damaged_books: "",
      total_fine_collected: "",

      userInfo: {},

      time: {
        weekday: "",
        day: "",
        month: "",
        year: "",     
      },
      loading2: false,
      advanced: true,
      columns: columns,
      dataSource1: [],
      dataSource2: [],
      selectedRows: [],
      loading: true,
      options: [],
      searchQuery: {
        book_name: "",
        author: "",
        publisher: "",
        ISBN: "",
        category: undefined,
        date: ""
      }
    };
  },
  methods: {
    changeContent(x) {
      this.$emit("changeContent", x);
    },
    getUserInfo() {
      this.loading = true;
      this.userInfo.avatar = getUserInfo().avatar;
      let myHeaders = new Headers({ "Content-Type": "application/json" });
      myHeaders.append("token", getAccessToken());
      console.log;
      let requestOptions = {
        method: "GET",
        headers: myHeaders,
      };

      let that = this;
      fetch(`${this.$global.BASE_URL}/api/user/profile/detail`, requestOptions)
        .then((response) => response.json())
        .then((result) => {
          console.log(result);
          that.userInfo.id = result.data.id;
          that.userInfo.name = result.data.name;
          that.userInfo.gender = result.data.gender;
          that.userInfo.position = result.data.position;
          that.userInfo.phone_number = result.data.phone_number;
          that.userInfo.email = result.data.email;
          that.userInfo.user_id = result.data.user_id;
          that.userInfo.borrowing = result.data.borrowings;
          that.userInfo.maxBorrowing = result.data.max_borrowing;
        })
        .catch((error) => console.log("error", error));
    },
    getDashboardInfo() {
      let myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());
      let requestoptions = {
        method: "GET",
        headers: myHeaders,
      };
      let that = this;
      fetch(`${this.$global.BASE_URL}/api/admin/dashboard`, requestoptions)
        .then((response) => response.json())
        .then((result) => {
          console.log(result);
          if (result.code == 0) {
            this.total_readers = result.data.total_readers;
            this.total_books = result.data.total_books;
            this.total_book_copys = result.data.total_book_copys;
            this.total_borrowings = result.data.total_borrowings;
            this.total_fine = result.data.total_fine;
            this.total_lost_books = result.data.total_lost_books;
            this.total_damaged_books = result.data.total_damaged_books;
            this.total_fine_collected = result.data.total_fine_collected;
          }
        })
        .catch((error) => console.log("error", error));
    },
    getTime() {
      let now = new Date();
      let weekday = now.getDay();
      switch (weekday) {
        case 1:
          this.time.weekday = "Mon";
          break;
        case 2:
          this.time.weekday = "Tue";
          break;
        case 3:
          this.time.weekday = "Wes";
          break;
        case 4:
          this.time.weekday = "Thu";
          break;
        case 5:
          this.time.weekday = "Fri";
          break;
        case 6:
          this.time.weekday = "Sat";
          break;
        case 0:
          this.time.weekday = "Sun";
          break;
      }
      this.time.day = now.getDate();
      let month = now.getMonth();
      switch (month) {
        case 0:
          this.time.month = "Jan";
          break;
        case 1:
          this.time.month = "Feb";
          break;
        case 2:
          this.time.month = "Mar";
          break;
        case 3:
          this.time.month = "Apr";
          break;
        case 4:
          this.time.month = "May";
          break;
        case 5:
          this.time.month = "Jun";
          break;
        case 6:
          this.time.month = "Jul";
          break;
        case 7:
          this.time.month = "Aug";
          break;
        case 8:
          this.time.month = "Sept";
          break;
        case 9:
          this.time.month = "Oct";
          break;
        case 10:
          this.time.month = "Nov";
          break;
        case 11:
          this.time.month = "Dec";
          break;
      }

      this.time.year = now.getFullYear();

      console.log(this.time);
    },
    deleteRecord(key) {
      this.dataSource1 = this.dataSource1.filter((item) => item.key !== key);
      // this.selectedRows = this.selectedRows.filter((item) => item.key !== key);
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    
    
    handleMenuClick(e) {
      if (e.key === "delete") {
        this.remove();
      }
    },
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
    onChangeGategory(value, selectedOptions) {
      console.log(value, selectedOptions);
    },
    search1(){
      var myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());

      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
      };
      this.loading = true;
      let that = this;
      // fetch(`${this.$global.BASE_URL}/api/book/search?book_name=${this.searchQuery.book_name}&author=${this.searchQuery.author}&publisher=${this.searchQuery.publisher}&ISBN=${this.searchQuery.ISBN}&category=${this.getFormatCatgory()}&pub_year=${this.searchQuery.date?this.searchQuery.date.year():''}&pub_month=${this.searchQuery.date?this.searchQuery.date.month():''}`, requestOptions)
      fetch(`${this.$global.BASE_URL}/api/admin/searchBorrowedBook`, requestOptions)
      .then(response => response.json())
        .then(result => {
          if (result.code == 0 || result.code == "0") {
            setTimeout(() => {
              that.dataSource1 = [];
              for(let i of result.data){
                that.dataSource1.push({
                  key: i.ISBN,
                  cover: i.cover,
                  book_name: i.book_name,
                  brief_introduction: i.brief_introduction+"",
                  publisher: i.publisher,
                  published_time: i.published_time,
                  author: i.author,
                  category: i.status
                })
              }
              that.loading = false;
            }, 200);
          }else{
            that.$messgae.error(result.msg)
            that.loading = false;
          }
        })
        .catch(error => {that.$messgae.error("API call failed.");that.loading = false});
    },
    search2(){
      var myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());

      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
      };
      this.loading = true;
      let that = this;
      // fetch(`${this.$global.BASE_URL}/api/book/search?book_name=${this.searchQuery.book_name}&author=${this.searchQuery.author}&publisher=${this.searchQuery.publisher}&ISBN=${this.searchQuery.ISBN}&category=${this.getFormatCatgory()}&pub_year=${this.searchQuery.date?this.searchQuery.date.year():''}&pub_month=${this.searchQuery.date?this.searchQuery.date.month():''}`, requestOptions)
      fetch(`${this.$global.BASE_URL}/api/admin/searchMostPopularBook`, requestOptions)
      .then(response => response.json())
        .then(result => {
          if (result.code == 0 || result.code == "0") {
            setTimeout(() => {
              that.dataSource2 = [];
              for(let i of result.data){
                that.dataSource2.push({
                  key: i.ISBN,
                  cover: i.cover,
                  book_name: i.book_name,
                  brief_introduction: i.brief_introduction+"",
                  publisher: i.publisher,
                  published_time: i.published_time,
                  author: i.author,
                  category: i.status
                })
              }
              that.loading = false;
            }, 200);
          }else{
            that.$messgae.error(result.msg)
            that.loading = false;
          }
        })
        .catch(error => {that.$messgae.error("API call failed.");that.loading = false});
    },
    resetQuery(){
      this.searchQuery = {
        book_name: "",
        author: "",
        publisher: "",
        ISBN: "",
        category: undefined,
        date: ""
      }
    }
  },
  async created() {
    this.getDashboardInfo();
    this.getUserInfo();
    this.getTime();
    this.search1();
    this.search2();
    // this.loading = true;
    // this.options = await category.getOptions();
    // let myHeaders = new Headers();
    // myHeaders.append("token", getAccessToken());

    // let requestoptions = {
    //   method: "GET",
    //   headers: myHeaders,
    // };
    // let that = this;
    // fetch(`${this.$global.BASE_URL}/api/admin/book/getAll?page_size=100&current_page=1`, requestoptions)
    //   .then((response) => response.json())
    //   .then((result) => {
    //     if (result.code == 0 || result.code == "0") {
    //       setTimeout(() => {
    //         for(let i of result.data.slice(1)){
    //           that.dataSource.push({
    //             key: i.ISBN,
    //             cover: i.cover,
    //             book_name: i.book_name,
    //             brief_introduction: i.brief_introduction+"",
    //             publisher: i.publisher,
    //             published_time: i.published_time,
    //             author: i.author,
    //             category: i.status
    //           })
    //         }
    //         that.loading = false;
    //       }, 200);
    //     }else{
    //       that.loading = false;
          
    //     }
    //   })
    //   .catch((error) => {
    //     console.log("error", error); 
    //     that.loading = false;
    //     that.$message.error("API call failed.")
    //   });
  },
};
</script>

<style scoped lang="scss">
img {
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
</style>
  